package com.ribbon.config;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.NacosServiceManager;
import com.alibaba.cloud.nacos.ribbon.NacosServer;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.client.naming.core.Balancer;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.Server;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class WeightRule extends AbstractLoadBalancerRule {
    @Autowired
    private NacosDiscoveryProperties nacosDiscoveryProperties;

    @Autowired
    private NacosServiceManager nacosServiceManager;

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {
    }

    @Override
    public Server choose(Object o) {
        BaseLoadBalancer baseLoadBalancer = (BaseLoadBalancer) getLoadBalancer();
        String name = baseLoadBalancer.getName();
        String myCluster = nacosDiscoveryProperties.getClusterName();
        String myGroup = nacosDiscoveryProperties.getGroup();
        NamingService namingService = nacosServiceManager.getNamingService(nacosDiscoveryProperties.getNacosProperties());

        try {
            List<Instance> instances = namingService.selectInstances(name, myGroup, true);
            List<Instance> instancesCluster = instances.stream().filter(instance -> instance.getClusterName().equals(myCluster)).collect(Collectors.toList());
            instancesCluster = instancesCluster.isEmpty() ? instances : instancesCluster;
            Instance instance = MyWeightRule.getRandomWeight(instancesCluster);
            return new NacosServer(instance);
        } catch (NacosException e) {
            throw new RuntimeException(e);
        }
    }

    static class MyWeightRule extends Balancer{
        public static Instance getRandomWeight(List<Instance> hosts){
            return Balancer.getHostByRandomWeight(hosts);
        }
    }
}
